import React, { Component } from "react";
import { Select, Input, Button, Card, Table, message } from "antd";
import { PlusSquareTwoTone } from "@ant-design/icons";
import { reqGetProduct, reqRemoveProduct } from "../../api/index";
import LinkButton from "../../component/LinkButton";
const { Option } = Select;
export default class PdtHome extends Component {
  state = {
    productList: [],
    inputValue: "",
    params: {
      pageNum: 1,
      pageSize: 8,
    },
    loading: false,
    totalPages: 0,
    selectValue: 1,
  };
  //得到的数据处理
  handleData = (data) => {
    data.forEach((element) => {
      element.name_id = element._id + element.name;
      element.desc_id = element._id + element.desc;
      element.price_id = element._id + element.price_id;
      element.status_id = element._id + element.status;
    });
  };
  //根据字段搜索数据的方法
  searchProductList = async (params, productName, productDesc) => {
    this.setState({ loading: true });
    const productList = await reqGetProduct(params, productName, productDesc);

    this.setState({ loading: false });
    if (productList.status !== 0) {
      message.error("获取商品列表失败");
      return;
    }
    //存储商品列表数据

    this.setState({
      productList: productList.data.list,
      totalPages: productList.data.total,
    });
  };
  //请求商品列表数据的方法并储存
  getProductList = async (params, productName, productDesc) => {
    this.setState({ loading: true });
    const productList = await reqGetProduct(params, productName, productDesc);

    this.setState({ loading: false });
    if (productList.status !== 0) {
      message.error("获取商品列表失败");
      return;
    }
    //存储商品列表数据
    const productListA = this.state.productList.concat(productList.data.list);
    this.handleData(productListA);
    this.setState({
      productList: productListA,
      totalPages: productList.data.total,
    });
  };
  //页码改变的回调函数
  onChange = async (page) => {
    await this.setState({
      params: {
        pageNum: page,
        pageSize: this.state.pageSize,
      },
    });
    this.getProductList(this.state.params);
  };
  //处理输入框输入的函数
  handleInput = (e) => {
    this.setState({
      inputValue: e.target.value,
    });
  };
  //左上角的选择框毁掉函数
  handleSelectChange = (e) => {
    console.log("selcet", e);
    if (e === "name") {
      this.setState({ selectValue: 1 });
    } else {
      this.setState({ selectValue: 2 });
    }
  };
  //搜索按钮点击事件
  handleSearch = async () => {
    if (!this.state.inputValue) {
      message.warning("请输入需要查询的字段");
      return;
    }
    await this.setState({
      params: {
        pageNum: 1,
        pageSize: 8,
      },
    });
    if (this.state.selectValue === 1) {
      this.searchProductList(this.state.params, this.state.inputValue);
    } else {
      this.searchProductList(this.state.params, "", this.state.inputValue);
    }

    message.success("你搜索的商品已找到");
  };
  //下架哈数
  handleRemove = async (e, record) => {
    const res = await reqRemoveProduct(record._id, record.status);
    if (res.status !== 0) {
      record.status === "1"
        ? message.error("下架失败")
        : message.error("上架失败");
    } else {
      message.success("修改商品状态成功");
    }
    this.getProductList(this.state.params);
  };
  //处理添加商品
  handleUpdate = () => {
    this.props.history.push("/product/update");
  };
  //组件将要渲染生命周期函数
  UNSAFE_componentWillMount() {
    //获取商品列表
    this.getProductList(this.state.params);
  }
  //-------------------------render
  render() {
    //结构state中的数据
    const { loading, productList, totalPages, params, inputValue } = this.state;
    const { pageSize, pageNum } = params;
    //Cart title部分配置
    const title = (
      <span>
        <Select
          defaultValue="name"
          style={{ width: 120 }}
          onChange={this.handleSelectChange}
        >
          <Option value="name">按名称搜索</Option>
          <Option value="desc">按描述搜索</Option>
        </Select>
        <Input
          placeholder="关键字"
          style={{ width: 180, margin: "0px 10px" }}
          value={inputValue}
          onChange={this.handleInput}
        />
        <Button type="primary" onClick={this.handleSearch}>
          搜索
        </Button>
      </span>
    );

    const dataSource = productList;

    const columns = [
      {
        title: "商品名称",
        dataIndex: "name",
        key: "name_id",
        width: 220,
        textWrap: "word-break",
        ellipsis: true,
      },
      {
        title: "商品描述",
        dataIndex: "desc",
        key: "desc_id",
        width: 1100,
        textWrap: "word-break",
        ellipsis: true,
      },
      {
        title: "价格",
        dataIndex: "price",
        key: "price_id",
        textWrap: "word-break",
        ellipsis: true,
        render: (e) => <span>￥{e}</span>,
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status_id",
        textWrap: "word-break",
        ellipsis: true,
        render: (e, record) => {
          if (e === 1) {
            return (
              <span>
                <Button
                  type="primary"
                  onClick={() => this.handleRemove(e, record)}
                >
                  下架
                </Button>
                <div>在售</div>
              </span>
            );
          } else {
            return (
              <span>
                <Button
                  type="primary"
                  onClick={() => this.handleRemove(e, record)}
                >
                  上架
                </Button>
                <div>已下架</div>
              </span>
            );
          }
        },
      },
      {
        title: "操作",
        dataIndex: "",
        key: "_id",
        render: (data) => (
          <span>
            <div>
              <LinkButton
                onClick={() => {
                  this.props.history.push({
                    pathname: "/product/detail",
                    state: data,
                  });
                }}
              >
                详情
              </LinkButton>
            </div>
            <div>
              <LinkButton>修改</LinkButton>
            </div>
          </span>
        ),
      },
    ];

    return (
      <Card
        style={{ height: "100%" }}
        title={title}
        extra={
          <Button type="primary">
            <PlusSquareTwoTone />
            <span onClick={this.handleUpdate}>添加商品</span>
          </Button>
        }
      >
        <Table
          loading={loading}
          dataSource={dataSource}
          columns={columns}
          bordered
          rowKey="_id"
          pagination={{
            pageSize: pageSize,
            onChange: this.onChange,
            total: totalPages,
            current: pageNum,
          }}
        />
      </Card>
    );
  }
}
